import flet as ft
from tools.text_utils import reverse_text


class TextToolsUI:
    def __init__(self, page, show_main_menu):
        self.page = page
        self.show_main_menu = show_main_menu
        self.setup_ui()

    def setup_ui(self):
        # 文本输入框
        self.text_input = ft.TextField(label="输入文本", hint_text="请输入文本")

        # 执行按钮
        self.reverse_button = ft.ElevatedButton(
            text="反转文本",
            on_click=self.on_reverse_button_click,
        )

        # 返回主菜单按钮
        self.back_button = ft.ElevatedButton(
            text="返回主菜单",
            on_click=lambda e: self.show_main_menu(),  # 使用 lambda 忽略事件参数
        )

        # 结果输出
        self.result_text = ft.Text()

    def build(self):
        return ft.Column(
            controls=[
                ft.Text("文本工具", size=20),
                self.text_input,
                self.reverse_button,
                self.back_button,
                self.result_text,
            ],
            spacing=20,
        )

    def on_reverse_button_click(self, e):
        text = self.text_input.value
        if not text:
            self.result_text.value = "请输入文本！"
        else:
            reversed_text = reverse_text(text)
            self.result_text.value = f"反转结果：{reversed_text}"
        self.page.update()
